<?php
header('Content-Type: application/json');

// 数据库配置
define('DB_HOST', 'localhost');
define('DB_NAME', 'music_db');
define('DB_USER', '73327382');
define('DB_PASS', '73327382');

// 获取参数
$keyword = filter_input(INPUT_GET, 'keyword', FILTER_SANITIZE_STRING) ?? '';
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

try {
    // 创建数据库连接
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // 根据ID查询
    if ($id !== false && $id !== null) {
        $sql = "SELECT id, title, artist, album, mp3_url FROM songs WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    }
    // 根据关键词搜索
    else if (!empty($keyword)) {
        $sql = "SELECT id, title, artist, album, mp3_url FROM songs 
                WHERE title LIKE :keyword OR artist LIKE :keyword OR album LIKE :keyword";
        $stmt = $pdo->prepare($sql);
        $searchTerm = "%" . $keyword . "%";
        $stmt->bindParam(':keyword', $searchTerm, PDO::PARAM_STR);
    }
    // 获取所有歌曲
    else {
        $sql = "SELECT id, title, artist, album, mp3_url FROM songs";
        $stmt = $pdo->prepare($sql);
    }
    
    // 执行查询
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 构建响应数据
    $response = [
        'status' => 'success',
        'count' => count($results),
        'results' => $results
    ];
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

} catch (PDOException $e) {
    // 数据库错误处理
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage(),
        'count' => 0,
        'results' => []
    ]);
} catch (Exception $e) {
    // 其他错误处理
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => 'An error occurred: ' . $e->getMessage(),
        'count' => 0,
        'results' => []
    ]);
}
?>